<template>
	<div>
		<slot name="changeOrgTitle"></slot>
		<div
			class="change-org change-org-component"
			:class="{ 'personal-style': isPersonalCenter }"
		>
			<div
				v-if="!props.isOutsideOrg && !props.labelId == '1'"
				class="handle-controls"
			>
				<a-select
					ref="select"
					v-model:value="dept_type"
					class="dept-type-filter"
					dropdownClassName="dept-type-filter-drop"
					@change="handleChange"
				>
					<a-select-option
						v-for="item in orgListOptions"
						:key="item.uid"
						:label="item.org_pattern_name"
						:value="item.org_pattern_code"
					>
						{{ item.org_pattern_name }}
					</a-select-option>
				</a-select>
				<a-input-search
					v-if="!props.isOutsideOrg"
					v-model:value="searchVal"
					class="dept-name-id-search"
					placeholder="搜索组织ID/名称"
					@search="onSearch"
					@pressEnter="searchPressEnter"
				/>
			</div>

			<div v-if="!orgList" class="no-org-list">
				<a-spin size="large" tip="Loading..." />
			</div>
			<div v-else class="org-data-list">
				<!-- 个人中心-行政组织-更多 -->
				<section v-if="isPersonalCenter">
					<ul class="org-list">
						<li v-for="(item, index) in orgList?.rows" :key="index">
							<div class="org-list-info">
								<div class="org-info">
									<div class="list-head">
										<span class="head-title">
											{{
												`${item.dept_name}${
													item.main_dept_flag
														? tenantDetail?.security_config_map?.main_lable_hide
															? ''
															: '(主)'
														: '（兼）'
												}`
											}}</span
										>
									</div>
									<div class="bottom-tips">
										<span class="o-id">
											{{ '组织ID：' + item.dept_id }}
										</span>
										<span v-if="item.org_pattern_name" class="o-type">
											{{ item.org_pattern_name }}
										</span>
									</div>
								</div>
							</div>
						</li>
					</ul>
				</section>
				<section v-else>
					<!-- 非外部 -->
					<ul v-if="!props.isOutsideOrg" class="org-list">
						<li
							v-for="(item, index) in orgList?.rows"
							:key="index"
							:class="{
								'org-active': checked_dep_id === item.dept_id,
							}"
							@click="checkItem(item.dept_id, item.label_id, index)"
						>
							<div class="org-list-info">
								<div class="org-info">
									<div class="list-head">
										<span class="head-title"> {{ item.dept_name }}</span>
									</div>
									<div class="bottom-tips">
										<span class="o-id">
											{{ '组织ID：' + item.dept_id }}
										</span>
										<span v-if="item.org_pattern_name" class="o-type">
											{{ item.org_pattern_name }}
										</span>
									</div>
								</div>
								<span v-if="item.default_dept_flag" class="default">默认</span>
							</div>
							<div class="default-flag">
								<img src="./img/checked.svg" />
							</div>
						</li>
					</ul>
					<!-- 外部 -->
					<ul v-else class="outside org-list">
						<li
							v-for="(item, index) in orgList"
							:key="index"
							class="org-list-item"
							:class="{
								'org-active': checked_dep_id === item.dept_id,
							}"
							@click="checkOutsideItem(item, index)"
						>
							<span class="outside-org" style="background-color: #4c78fc">{{
								item.dept_type_name
							}}</span>
							<span class="org-name" :title="item.dept_name">{{
								item.dept_name
							}}</span>
							<p class="org-id">id：{{ item.dept_id }}</p>
							<div class="default-flag">
								<img src="./img/checked.svg" />
							</div>
						</li>
					</ul>
				</section>
				<a-pagination
					v-if="!props.isOutsideOrg"
					class="change-org-pagination"
					v-model:current="orgPage.current"
					defaultPageSize="20"
					:total="orgList?.page?.total_count"
					:page-size-options="pageSizeOptions"
					show-size-changer
					@showSizeChange="showSizeChange"
					:show-total="(total:number) => `共 ${total} 条数据`"
				/>
				<div v-if="!isPersonalCenter" class="bottom-buttons">
					<button
						v-if="props.isOutsideOrg"
						class="org-list-btn real"
						type="primary"
						@click="changeOutsideOrg"
					>
						切换
					</button>
					<div v-else>
						<a-button
							class="org-list-btn real"
							type="primary"
							:disabled="checked_dep_id == '' || button_disabled"
							@click="changeOrg"
						>
							切换
						</a-button>
						<a-button
							class="org-list-btn real change-org-d"
							type="primary"
							:disabled="checked_dep_id == '' || button_disabled"
							@click="changeOrg('switchAndSetDefault')"
						>
							切换并设为默认
						</a-button>
					</div>
					<a-button
						class="org-list-btn cancel"
						@click="emits('showChangeOrg', false)"
					>
						取消
					</a-button>
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { apiInit } from '@/services'
import { ref, onMounted, reactive, watch, onUnmounted, createVNode } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { useStore } from 'vuex'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { cloneDeep } from 'lodash'
const api = apiInit()
const orgList = ref()
const emits = defineEmits(['showChangeOrg'])
const store = useStore()
const checked_dep_id = ref('')
//控制按钮disabled
const button_disabled = ref(false)
const tenantDetail = ref({})

const props = defineProps({
	isOutsideOrg: {
		type: Boolean,
	},
	isPersonalCenter: {
		type: Boolean,
		default: false,
	},
	labelId: {
		type: String,
		default: '',
	},
	orgDetail: {
		type: Object,
		default: () => {},
	},
	isDept: {
		type: Boolean,
	},
})
//搜索文字和id
const searchVal = ref('')
//组织形态
const dept_type = ref('')
const pageSizeOptions = ['10', '20', '50', '100']
onMounted(() => {
	getOrgType()
	tenantDetail.value = JSON.parse(
		localStorage.getItem('tenantDetail') || ''
	).data
})
//组织形态列表
const orgListOptions: any = ref([])
//获取组织形态
const getOrgType = async () => {
	const res = await api.baseInfoNew.GetBizorgPatternList({})
	if (res.code == '000000') {
		orgListOptions.value = res.data
		orgListOptions.value.unshift({
			org_pattern_code: 'all',
			org_pattern_name: '全部形态',
			uid: 'all',
		})
		dept_type.value = 'all'
	}
}
const orgPage = reactive({
	current: 1,
	searchText: '',
	org_pattern_code: '',
	page_size: 20,
})
//获取组织列表
const fetchOrgList = async () => {
	let params: any =
		props.labelId == '1'
			? {
					dept_name_like: orgPage.searchText,
					employee_id: '',
					label_id: props.labelId,
					page_index: orgPage.current,
					page_size: orgPage.page_size,
					tenant_id: '',
					org_pattern_code: orgPage.org_pattern_code,
			  }
			: {
					dept_name_like: orgPage.searchText,
					employee_id: '',
					page_index: orgPage.current,
					page_size: orgPage.page_size,
					tenant_id: '',
					org_pattern_code: orgPage.org_pattern_code,
			  }
	let result: any
	if (props.labelId == '1') {
		result = await api.baseAuto.PageInternalMulDeptPrivateV1POST({
			payload: params,
		})
	} else {
		result = await api.baseInfoNew.getOrgList(params)
	}
	return result
}
//搜索回车
const searchPressEnter = (val: any) => {}
const onSearch = (val: any) => {
	orgPage.current = 1
	orgPage.searchText = val
}
// 每页显示条数切换
const showSizeChange = (current: any, size: any) => {
	orgPage.current = 1
	orgPage.page_size = size
}
const changeOrgParams = reactive({
	deptId: '',
	labelId: '',
})
const changeOutsideOrgParams = ref('')
//组织切换
const changeOrg = (val: any) => {
	Modal.confirm({
		title: '切换后将刷新当前页面，未保存的数据将丢失，请确认',
		icon: createVNode(ExclamationCircleOutlined),
		content: '',
		okText: '切换',
		cancelText: '取消',
		onOk() {
			changeOrgSwitch(val)
		},
		onCancel() {
			console.log('Cancel')
		},
	})
}
const changeOrgSwitch = async (val: any) => {
	const parm: any = {
		deptId: changeOrgParams.deptId,
		labelId: changeOrgParams.labelId,
		defaultOrg: val == 'switchAndSetDefault' ? '1' : undefined,
	}
	let { code, message: Msg } =
		await api.baseAuto.SwitchDeptEmployeePrivateV1POST({
			query: parm,
		})
	if (code === '000000') {
		setTimeout(() => {
			window.location.reload()
		}, 500)
	} else {
		message.error(Msg!)
	}
}
const changeOutsideOrg = async () => {
	let { code, message: Msg } =
		await api.baseAuto.SwitchDeptExternalEmployeePrivateV1POST({
			query: {
				employeeId: changeOutsideOrgParams.value,
			},
		})
	if (code === '000000') {
		window.location.reload()
	} else {
		message.error(Msg!)
	}
}
//切换并设为默认
const changeOrgAndSetDefault = (org_type: string) => {}
const checkItem = (dept: string, label: string, index: number) => {
	checked_dep_id.value = dept
	button_disabled.value = false
	;[changeOrgParams.deptId, changeOrgParams.labelId] = [dept, label]
}
const checkOutsideItem = (item: any, index: number) => {
	checked_dep_id.value = item.dept_id
	changeOutsideOrgParams.value = item.employee_id
}
const fetchOutsideList = async () => {
	let { data, code, msg } = await api.baseAuto.ListExternalMulDeptPrivateV1POST(
		{}
	)
	if (code === '000000') {
		return data
	} else {
		message.error(msg!)
	}
}
const setDefault = async (
	newDeptId: string,
	newLabelId: string,
	oldDeptId: string,
	oldLableId: string
) => {
	let params: any = {
		new_dept_id: newDeptId,
		new_label_id: newLabelId,
		old_dept_id: oldDeptId,
		old_label_id: oldLableId,
	}
	let { code } = await api.baseAuto.SetDefaultDeptInternalMulDeptPrivateV1POST({
		payload: params,
	})
	if (code === '000000') {
		message.success('设置默认组织成功')
		window.location.reload()
	}
}
//组织形态筛选
const handleChange = (val: string) => {
	let org_pattern_code = ''
	if (val != 'all') {
		org_pattern_code = val
	}
	searchVal.value = ''
	orgPage.searchText = ''
	orgPage.current = 1
	orgPage.org_pattern_code = org_pattern_code
}
watch(
	() => orgPage,
	async () => {
		if (!props.isOutsideOrg) {
			orgList.value = await fetchOrgList()
			orgList.value.rows.forEach((item: any, index: any) => {
				if (item.dept_id === props.orgDetail.cur_dept?.dept_id) {
					checked_dep_id.value = item.dept_id
				}
			})
			button_disabled.value = !orgList.value.rows.some(
				(a: any) => a.dept_id == checked_dep_id.value
			)
		} else {
			orgList.value = await fetchOutsideList()
			orgList.value.forEach((item: any, index: any) => {
				if (item.dept_id === props.orgDetail.department_id) {
					checked_dep_id.value = item.dept_id
				}
			})
			button_disabled.value = !orgList.value.some(
				(a: any) => a.dept_id == checked_dep_id.value
			)
			store.commit('setOutsideOrgList', orgList.value)
		}
	},
	{
		deep: true,
		immediate: true,
	}
)
</script>

<style lang="less">
.change-org-component {
	box-sizing: border-box;
	padding: 24px 24px;
	margin-bottom: 20px;
	background: #fff;
	border-radius: 8px;
	border-top-left-radius: 0;
	border-top-right-radius: 0;
	overflow: hidden;
	padding-top: 0;
	min-width: 500px;
	width: 40vw;
	min-height: 550px;
	height: 80vh;
	position: relative;
	.handle-controls {
		.ant-select .ant-select-selector {
			background-color: #f2f4f7;
			border: none;
			height: 30px;
		}
		.ant-input-search {
			background-color: #f2f4f7;
			border: none;
			.ant-input,
			.ant-input-search-button {
				background-color: #f2f4f7;
				border: none;
			}
		}
	}
	.no-org-list {
		width: 100%;
		height: 300px;
		background-color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.org-data-list {
		height: calc(100% - 154px);
		section {
			height: 100%;
		}
	}
	.org-type-main {
		background: #ebf1ff;
		border-radius: 12px;
		font-family: 'PingFang SC';
		font-style: normal;
		font-weight: 400;
		line-height: 100%;
		padding: 4px;
		box-sizing: border-box;
	}
	.org-type {
		max-width: 70px;
		min-width: 32px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		height: 16px;
		padding: 2px 4px;
		border-radius: 2px;
		font-family: 'PingFang SC';
		font-style: normal;
		font-weight: 400;
		font-size: 12px;
		line-height: 100%;
		color: #ffffff;
		margin-right: 5px;
	}
	.org-utype {
		font-family: 'PingFang SC';
		font-style: normal;
		font-weight: 400;
		font-size: 14px;
		line-height: 18px;
		color: #1f2329;
		padding-left: 4px;
	}
	.org-name {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	&-title {
		display: flex;
		align-items: center;
		width: 100%;
		height: 32px;
		padding: 0 10px;
		border-radius: 4px;
		background-color: var(--bl-brand-label);
		margin-bottom: 12px;
		span:first-child {
			font-family: 'PingFang SC';
			font-style: normal;
			font-weight: 400;
			font-size: 14px;
			line-height: 20px;
			color: #646a73;
			white-space: nowrap;
		}
	}
	.ant-pagination {
		display: flex;
		justify-content: flex-end;
		.ant-pagination-options {
			.ant-select.ant-pagination-options-size-changer.ant-select-single.ant-select-show-arrow {
				margin-right: 0;
			}
		}
	}
	.org-list-btn {
		float: right;
		font-family: 'PingFang SC';
		font-style: normal;
		font-weight: 500;
		font-size: 14px;
		line-height: 14px;
		padding: 0px 17px;
		cursor: pointer;
	}
	.cancel {
		margin-right: 8px;
		background: #ffffff;
		color: #000;
		border: 1px solid #e8eaed;
		border-radius: 4px;
		&:hover {
			background: var(--bl-n100-c);
		}
		&:active {
			background: var(--bl-n300-c);
		}
	}
	.change-org-d {
		margin-right: 8px;
	}
	.ant-input-affix-wrapper {
		height: 40px;
		width: 100%;
		margin-bottom: 12px;
	}

	.org-list {
		min-width: 350px;
		max-height: 100%;
		overflow-y: scroll;
		&::-webkit-scrollbar {
			width: 0;
		}

		li {
			display: flex;
			align-items: center;
			padding: 0 100px 0 12px;
			height: 66px;
			border-radius: 4px;
			border: 1px solid #dee0e3;
			background-color: #fff;
			margin-top: 12px;
			cursor: pointer;
			position: relative;
			user-select: none;
			.org-type {
				max-width: 70px;
				min-width: 32px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				height: 16px;
				padding: 2px 4px;
				border-radius: 2px;
				font-family: 'PingFang SC';
				font-style: normal;
				font-weight: 400;
				font-size: 12px;
				line-height: 100%;
				color: #ffffff;
				margin-right: 5px;
			}
			p,
			.org-list-info {
				display: inline-block;
				max-width: 690px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.org-info {
				.list-head {
					position: absolute;
					top: 12px;
					left: 16px;
					.head-title {
						display: inline-block;
						margin-right: 4px;
					}
					.head-title {
						font-weight: 500;
						font-size: 14px;
						line-height: 20px;
						height: 20px;
						color: #1f2329;
					}
				}
				.bottom-tips {
					position: absolute;
					top: 36px;
					left: 16px;
					.o-id,
					.o-type {
						display: inline-block;
						margin-right: 4px;
					}

					.o-id,
					.o-type {
						background: #f2f4f7;
						border-radius: 4px;
						height: 20px;
						line-height: 20px;
						padding: 0 7px;
						font-size: 12px;
						line-height: 20px;
					}
				}
			}

			.set-default {
				position: absolute;
				right: 0;
				top: 10px;
				padding-right: 16px;
				width: 72px;
				line-height: 46px;
				font-family: 'PingFang SC';
				font-style: normal;
				font-weight: 500;
				font-size: 14px;
				color: var(--bl-brand-c);
				visibility: hidden;
				text-align: end;
				user-select: none;
				&:active {
					color: var(--bl-brand-active);
				}
				&:hover {
					color: var(--bl-brand-hover);
				}
			}

			.default {
				display: inline-block;
				width: 36px;
				height: 22px;
				line-height: 20px;
				text-align: center;
				font-family: 'PingFang SC';
				font-style: normal;
				font-weight: 500;
				font-size: 12px;
				position: absolute;
				top: 22px;
				right: 16px;
				border-radius: 3px;
				color: #646a73;
				border: 1px solid #dee0e3;
				background-color: #fff;
			}
			img {
				display: none;
			}
		}
		.org-active {
			position: relative;
			border-color: transparent;
			background: #f2f4f7;
			border: 1px solid var(--bl-brand-c);
			overflow: hidden;
			.outside-org {
				background-color: var(--bl-brand-c);
				color: #fff;
				border-color: transparent;
			}
			.default {
				color: var(--bl-brand-c);
				border: 1px solid var(--bl-brand-hover);
				background-color: #f2f4f7;
			}
			.default-flag {
				width: 50px;
				height: 50px;
				background-color: var(--bl-brand-c);
				position: absolute;
				top: -30px;
				right: -30px;
				transform: rotate(45deg);
			}

			img {
				display: inline-block;
				position: absolute;
				width: 11px;
				top: 38px;
				right: 20px;
				transform: rotate(-45deg);
			}
		}
		li:first-child {
			margin-top: 0;
		}
		li:hover {
			background: #f2f4f7;
			border: 1px solid var(--bl-brand-c);
			p,
			.org-list-info {
				.set-default {
					visibility: visible;
				}
				.default {
					color: var(--bl-brand-c);
					border: 1px solid var(--bl-brand-hover);
					background-color: #f2f4f7;
				}
				.o-id,
				.o-type {
					color: #8f959e;
					background: #ffffff;
				}
			}
		}
		.default {
			background: #ebf1ff;
			border-color: transparent;
		}
	}
	.personal-list {
		max-width: 800px;
		min-width: 350px;
		max-height: 344px;
		overflow-y: scroll;
		margin-bottom: 14px;
		&::-webkit-scrollbar {
			width: 0;
		}
		li {
			display: flex;
			align-items: center;
			padding-right: 12px;
			max-width: 800px;
			height: 48px;
			background-color: #fff;
			position: relative;
			.org-type {
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				max-width: 70px;
				min-width: 32px;
				height: 16px;
				padding: 2px 4px;
				border-radius: 2px;
				font-family: 'PingFang SC';
				font-style: normal;
				font-weight: 400;
				font-size: 12px;
				line-height: 100%;
				color: #ffffff;
				margin-right: 5px;
			}
			p,
			.org-list-info {
				display: inline-block;
				max-width: 690px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}
	}
	.outside {
		li {
			display: block;
			padding: 12px;
			height: auto;
			padding-top: 6px;
			.org-id {
				display: block;
			}
			.outside-org {
				max-width: 70px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				display: inline-block;
				background: #ebf1ff;
				border: 1px solid #4c78fc;
				border-radius: 2px;
				font-family: 'PingFang SC';
				font-style: normal;
				font-weight: 400;
				font-size: 12px;
				line-height: 100%;
				color: #fff;
				padding: 2px 4px;
				margin-right: 5px;
			}
			.org-name {
				display: inline-block;
				max-width: calc(100% - 70px);
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				position: relative;
				top: 6px;
			}
			.org-id {
				font-family: 'PingFang SC';
				font-style: normal;
				font-weight: 400;
				font-size: 14px;
				line-height: 20px;
				color: #8f959e;
			}
		}
	}
	.ant-pagination-options .ant-select {
		margin-right: 0;
	}
	.handle-controls {
		margin-bottom: 12px;
		.dept-type-filter,
		.dept-name-id-search {
			width: calc(50% - 8px);
			display: inline-block;
		}
		.dept-type-filter {
			margin-right: 16px;
		}
		.dept-name-id-search {
		}
	}
	+ img {
		position: absolute;
		top: 8px;
		left: -22px;
	}
	.change-org-pagination {
		position: absolute;
		width: calc(100% - 48px);
		bottom: 78px;
	}
	.bottom-buttons {
		position: absolute;
		width: calc(100% - 48px);
		bottom: 24px;
	}
}
.personal-style {
	position: initial;
	transform: scale(1);
}
.dept-type-filter-drop {
	z-index: 999;
}
</style>
